import cv2
import numpy as np


def empty(a):
    pass


cv2.namedWindow('TrackBars')
cv2.resizeWindow('TrackBars', 380, 480)

cv2.createTrackbar('Hue Min', 'TrackBars', 0, 255, empty)
cv2.createTrackbar('Hue Max', 'TrackBars', 255, 255, empty)
cv2.createTrackbar('Sat Min', 'TrackBars', 0, 255, empty)
cv2.createTrackbar('Sat Max', 'TrackBars', 255, 255, empty)
cv2.createTrackbar('Val Min', 'TrackBars', 0, 255, empty)
cv2.createTrackbar('Val Max', 'TrackBars', 255, 255, empty)

cv2.createTrackbar('R', 'TrackBars', 0, 255, empty)
cv2.createTrackbar('G', 'TrackBars', 0, 255, empty)
cv2.createTrackbar('B', 'TrackBars', 0, 255, empty)

cv2.createTrackbar('Bin Min', 'TrackBars', 0, 255, empty)
cv2.createTrackbar('Bin Max', 'TrackBars', 255, 255, empty)

while True:
    img = cv2.imread('result.jpg')
    img = cv2.resize(img, None, fx=1.2, fy=1.2, interpolation=cv2.INTER_CUBIC)
    imgHSV = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
    imgGray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    h_min = cv2.getTrackbarPos('Hue Min', 'TrackBars')
    h_max = cv2.getTrackbarPos('Hue Max', 'TrackBars')
    s_min = cv2.getTrackbarPos('Sat Min', 'TrackBars')
    s_max = cv2.getTrackbarPos('Sat Max', 'TrackBars')
    v_min = cv2.getTrackbarPos('Val Min', 'TrackBars')
    v_max = cv2.getTrackbarPos('Val Max', 'TrackBars')

    lower = np.array([h_min, s_min, v_min])
    upper = np.array([h_max, s_max, v_max])
    mask = cv2.inRange(imgHSV, lower, upper)

    r = cv2.getTrackbarPos('R', 'TrackBars')
    g = cv2.getTrackbarPos('G', 'TrackBars')
    b = cv2.getTrackbarPos('B', 'TrackBars')
    print(f'h_min:{h_min},h_max:{h_max},s_min:{s_min},s_max:{s_max},v_min:{v_min},v_max:{v_max},r:{r},g:{g},b:{b}')

    bin_min = cv2.getTrackbarPos('Bin Min', 'TrackBars')
    bin_max = cv2.getTrackbarPos('Bin Max', 'TrackBars')
    bin_ret, bin_mask = cv2.threshold(imgGray, bin_min, bin_max, cv2.THRESH_BINARY)

    img2 = np.copy(img)
    img2[:] = [b, g, r]
    bitwise = cv2.bitwise_and(img2, img2, mask=bin_mask)
    merge = cv2.addWeighted(cv2.bitwise_and(img, img, mask=mask), 1, bitwise, 1, 0)

    cv2.imshow('Original Image', img)
    cv2.imshow('Mask', mask)
    cv2.imshow('Binary Mask', bin_mask)
    cv2.imshow('Bitwise Operation', bitwise)
    cv2.imshow('Merged Layer', merge)

    cv2.waitKey(1)
    if cv2.getWindowProperty('TrackBars', 0) == -1:
        break
cv2.destroyAllWindows()
